package com.aabte.cases;

import com.aabte.config.TestConfig;
import com.aabte.model.GetUserInfoCase;
import com.aabte.model.User;
import com.aabte.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;

public class GetUserInfoTest {

    @Test(dependsOnGroups = "loginTrue", description = "获取用户ID为1的用户信息")
    public void getUserInfo() throws IOException {
        SqlSession session = DatabaseUtil.getSqlSession();
        GetUserInfoCase getUserInfoCase = session.selectOne("getUserInfoCase", 1);
        System.out.println(getUserInfoCase);
        System.out.println(TestConfig.getUserInfoUrl);

        JSONArray resultJson = getJsonResult(getUserInfoCase);
        Assert.assertNotNull(resultJson);
        Assert.assertEquals(resultJson.length(), 1);
        JSONObject actual = resultJson.getJSONObject(0);

        User user = session.selectOne(getUserInfoCase.getExpected(), getUserInfoCase.getUserId());
        JSONObject expect = new JSONObject(user);

        Assert.assertEquals(expect.get("id"), actual.get("id"));
        Assert.assertEquals(expect.get("username"), actual.get("username"));
        Assert.assertEquals(expect.get("password"), actual.get("password"));
        Assert.assertEquals(expect.get("sex"), actual.get("sex"));
        Assert.assertEquals(expect.get("age"), actual.get("age"));
        Assert.assertEquals(expect.get("permission"), actual.get("permission"));
        Assert.assertEquals(expect.get("isDelete"), actual.get("isDelete"));

    }

    private JSONArray getJsonResult(GetUserInfoCase getUserInfoCase) throws IOException {

        HttpPost post = new HttpPost(TestConfig.getUserInfoUrl);
        JSONObject param = new JSONObject();
        param.put("id", getUserInfoCase.getUserId());

        post.setHeader("Content-type", "application/json");

        StringEntity entity = new StringEntity(param.toString());
        post.setEntity(entity);

        HttpResponse response = TestConfig.httpClient.execute(post);

        String result = EntityUtils.toString(response.getEntity());

        try {
            JSONArray jsonArray = new JSONArray(result);
            return jsonArray;
        } catch (Exception e) {
            return null;
        }
    }
}
